package com.xbongbong.crm.perform.query.render.edit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmEditPageRenderService;
import com.xbongbong.crm.feign.FormDataFeign;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.ButtonGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateGetDTO;
import com.xbongbong.paas.pojo.vo.ButtonGetVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.formdata.pojo.SaasSpecialParamPojo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.help.FormatProductHelp;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/06/13 17:27
 */
@Service("refundEditPageRenderServiceImpl")
@Slf4j
public class RefundEditPageRenderServiceImpl extends AbstractCrmEditPageRenderService {

    @Resource
    private RefundModel refundModel;
    @Resource
    private FormatProductHelp formatProductHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private FormDataFeign formDataFeign;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.REFUND.getCode());
    }

    @Override
    public ParseSingleRowDataVO formatData(FormDataUpdateGetDTO formDataUpdateGetDTO, HandlerExplainVO handlerExplainVO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        String corpid = formDataUpdateGetDTO.getCorpid();
        Integer businessType = formDataUpdateGetDTO.getBusinessType();
        SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO(corpid, formDataUpdateGetDTO.getDataId(), formDataUpdateGetDTO.getBusinessType(), false, null);
        // saas特殊格式转换
        JSONObject data = paasFormDataEntityExt.getData();
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(handlerExplainVO.getHeadList());
        saasAnalysisDataDTO.setExplainMap(explainMap);
        refundModel.formatData(saasAnalysisDataDTO, data);
        // 红冲回款单
        JSONArray invoiceArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, RefundEnum.INVOICES.getAttr(), new JSONArray());
        JSONArray sheetArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, RefundEnum.PAYMENT_SHEETS.getAttr(), new JSONArray());
        JSONArray paymentArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, RefundEnum.PAYMENTS.getAttr(), new JSONArray());
        Integer distributorMark = formDataUpdateGetDTO.getDistributorMark();
        Locale locale = LocaleContextHolder.getLocale();
        String lang = locale.toString();
        if (CollectionsUtil.isNotEmpty(invoiceArray)) {
            List<Long> invoiceIds = new ArrayList<>();
            for (Object obj : invoiceArray) {
                JSONObject invoiceObj = (JSONObject) obj;
                invoiceIds.add(invoiceObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
            }
            if (invoiceIds.size() > 0) {
                PaasFormEntity paasFormEntity;
                if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                    paasFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.INVOICE.getCode(), corpid, distributorMark, null);
                } else {
                    paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), corpid);
                }
                ButtonGetDTO buttonGetDTO = new ButtonGetDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, buttonGetDTO);
                BeanUtil.copyProperties(paasFormEntity, buttonGetDTO);
                buttonGetDTO.setDataIdIn(invoiceIds);
                try{
                    buttonGetDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    XbbResponse<Object> xbbResponse = formDataFeign.buttonGet(buttonGetDTO, lang);
                    if (xbbResponse.isSuccess()) {
                        ButtonGetVO buttonGetVO = JSON.parseObject(JSON.toJSONString(xbbResponse.getResult()), ButtonGetVO.class);
                        data.put(RefundEnum.INVOICES.getAttr(), buttonGetVO.getDataList());
                    }
                } catch (Exception e){
                    if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                        data.put(RefundEnum.INVOICES.getAttr(), new ArrayList<>());
                    } else {
                        data.put(ReturnedPurchaseEnum.INVOICES.getAttr(), new ArrayList<>());
                    }
                    log.error("关联发票已删除", e);
                }
            }
        }

        if (CollectionsUtil.isNotEmpty(sheetArray)) {
            List<Long> paymentSheetIds = new ArrayList<>();
            for (Object obj : sheetArray) {
                JSONObject paymentObj = (JSONObject) obj;
                paymentSheetIds.add(paymentObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
            }
            if (paymentSheetIds.size() > 0) {
                PaasFormEntity paasFormEntity;
                ButtonGetDTO buttonGetDTO = new ButtonGetDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, buttonGetDTO);
                int redBusinessType;
                if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                    paasFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), corpid, distributorMark, null);
                    redBusinessType = XbbRefTypeEnum.RED_PAYMENT_SHEET.getCode();
                } else {
                    paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PAY_SHEET.getCode(), corpid);
                    redBusinessType = XbbRefTypeEnum.RED_WRITE_OFF_PAY.getCode();
                }
                BeanUtil.copyProperties(paasFormEntity, buttonGetDTO);
                buttonGetDTO.setBusinessType(redBusinessType);
                buttonGetDTO.setDataIdIn(paymentSheetIds);
                try {
                    buttonGetDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    XbbResponse<Object> xbbResponse = formDataFeign.buttonGet(buttonGetDTO, lang);
                    if (xbbResponse.isSuccess()) {
                        ButtonGetVO buttonGetVO = JSON.parseObject(JSON.toJSONString(xbbResponse.getResult()), ButtonGetVO.class);
                        data.put(RefundEnum.PAYMENT_SHEETS.getAttr(), buttonGetVO.getDataList());
                    }
                } catch (Exception e) {
                    if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                        data.put(RefundEnum.PAYMENT_SHEETS.getAttr(), new ArrayList<>());
                    } else {
                        data.put(ReturnedPurchaseEnum.PAY_SHEETS.getAttr(), new ArrayList<>());
                    }
                    log.error("关联回/付款单已删除", e);
                }
            }
        }

        if (CollectionsUtil.isNotEmpty(paymentArray)) {
            List<Long> paymentIds = new ArrayList<>();
            for (Object obj : paymentArray) {
                JSONObject paymentObj = (JSONObject) obj;
                paymentIds.add(paymentObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
            }
            if (paymentIds.size() > 0) {
                ButtonGetDTO buttonGetDTO = new ButtonGetDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, buttonGetDTO);
                int redBusinessType = XbbRefTypeEnum.PAYMENT.getCode();
                PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PAYMENT.getCode(), corpid, distributorMark, null);
                BeanUtil.copyProperties(paasFormEntity, buttonGetDTO);
                buttonGetDTO.setBusinessType(redBusinessType);
                buttonGetDTO.setDataIdIn(paymentIds);
                try {
                    buttonGetDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    XbbResponse<Object> xbbResponse = formDataFeign.buttonGet(buttonGetDTO, lang);
                    if (xbbResponse.isSuccess()) {
                        ButtonGetVO buttonGetVO = JSON.parseObject(JSON.toJSONString(xbbResponse.getResult()), ButtonGetVO.class);
                        data.put(RefundEnum.PAYMENTS.getAttr(), buttonGetVO.getDataList());
                    }
                } catch (Exception e) {
                    data.put(RefundEnum.PAYMENTS.getAttr(), new ArrayList<>());
                    log.error("关联应收款已删除", e);
                }
            }
        }
        boolean formCopy = Objects.nonNull(formDataUpdateGetDTO.getSaasSpecialParamPojo()) && Objects.equals(formDataUpdateGetDTO.getSaasSpecialParamPojo().getFromCopy(), BasicConstant.ONE);
        formatProductHelp.formatProduct(saasAnalysisDataDTO,data,handlerExplainVO.getHeadList(), formCopy);

        data.put(FieldTypeEnum.COUSERID.getAlias(), handlerExplainVO.getCoUserId());
        data.put(FieldTypeEnum.OWNERID.getAlias(), handlerExplainVO.getOwnerId());
        data.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEntityExt.getSerialNo());
        data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEntityExt.getDepartmentId());
        ParseSingleRowDataVO parseSingleRowDataVO = parseSingleRowData(formDataUpdateGetDTO, data, explainMap, handlerExplainVO.getUserMap(), handlerExplainVO.getDepartmentMap());

        // 模板数据
        paasFormDataEntityExt.setData(parseSingleRowDataVO.getResult());
        return parseSingleRowDataVO;
    }

    @Override
    public void businessHandleExplain(FormDataUpdateGetDTO formDataUpdateGetDTO, List<FieldAttrEntity> list, PaasFormEntityExt form, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        String corpid = formDataUpdateGetDTO.getCorpid();
        SaasSpecialParamPojo saasSpecialParamPojo = formDataUpdateGetDTO.getSaasSpecialParamPojo();
        boolean formCopy = Objects.nonNull(saasSpecialParamPojo) && Objects.equals(saasSpecialParamPojo.getFromCopy(), BasicConstant.ONE);
        // 编辑时saas字段显示特殊逻辑
        FormatExplainDTO formatExplainDTO = new FormatExplainDTO(corpid, list, formCopy, saasSpecialParamPojo, paasFormDataEntityExt, formDataUpdateGetDTO.getLoginUser());

        refundModel.formatUpdateExplain(formatExplainDTO);
    }

    @Override
    public void handelSaasSpecialUpdate(List<FieldAttrEntity> explainList, Integer businessType, PaasFormDataEntityExt formDataEntityExt, boolean formCopy, Integer distributorMark) throws XbbException {

    }
}
